#ifndef __EPOLL_SERVER_HPP__
#define __EPOLL_SERVER_HPP__

#include <iostream>
#include <string>
#include <functional>
#include "Epoll.hpp"
#include "Log.hpp"
#include "Sock.hpp"

namespace ns_epoll
{
    static const int default_port = 8080;
    static const int gnum = 64;

    class EpollServer
    {
        using func_t = std::function<void(std::string)>;
    public:
        EpollServer(func_t HandlerRequest,const int &port = default_port)
            :_port(port),_revs_num(gnum),_HandlerRequest(HandlerRequest)
        {
            //0,申请空间
            _revs = new struct epoll_event[_revs_num];
            //1,创建套接字
            _listensock = Sock::Socket();
            Sock::Bind(_listensock,_port);
            Sock::Listen(_listensock);
            //2，创建epoll模型
            _epfd = Epoll::CreateEpoll();
            logMessage(DEBUG,"init success,listensock: %d,epfd: %d",_listensock,_epfd);
            //3,将listensock,先添加到epoll,让epoll管理起来
            if(Epoll::CtlEpoll(_epfd,EPOLL_CTL_ADD,_listensock,EPOLLIN))
            {
                logMessage(DEBUG,"add listensock to epoll success");
            }
            else
            {
                exit(6);
            }
        }
        void Accepter(int listensock)
        {
            std::string clientip;
            uint16_t clientpor;
            int sock = Sock::Accept(listensock,&clientip,&clientpor);
            if(sock <0)
            {
                logMessage(WARNING,"accept error!");
                return;
            }
            if(!Epoll::CtlEpoll(_epfd,EPOLL_CTL_ADD,sock,EPOLLIN)) return;
            logMessage(DEBUG,"add new sock : %d to epoll success",sock);
        }
        void Recver(int sock)
        {
            //1，读取数据
            char buffer[10240];
            ssize_t n = recv(sock,buffer,sizeof(buffer)-1,0);
            if(n > 0)
            {
                buffer[n] = 0;
                _HandlerRequest(buffer);//2，处理数据
            }
            else if(n == 0)
            {
                //1.先在epoll中去掉对sock的关心
                bool res = Epoll::CtlEpoll(_epfd,EPOLL_CTL_DEL,sock,0);
                assert(res);
                (void)res;
                close(sock);
                logMessage(NORMAL,"client %d quit,me to...",sock);

                //2.再coles文件
            }
            else
            {
                //1.先在epoll中去掉对sock的关心
                bool res = Epoll::CtlEpoll(_epfd,EPOLL_CTL_DEL,sock,0);
                assert(res);
                (void)res;
                close(sock);
                logMessage(NORMAL,"client recv %d error,close error sock",sock);

            }
        }
        void HandlerEvent(int n)
        {
            assert(n>0);
            for(int i = 0;i<n;i++)
            {
                uint32_t revents = _revs[i].events;
                int sock = _revs[i].data.fd;
                if(revents & EPOLLIN)
                {
                    if(sock == _listensock) Accepter(_listensock);
                    else Recver(sock);
                }   
            }
        }
        void loopOnce(int timeout)
        {
            int n = Epoll::WaitEpoll(_epfd,_revs,_revs_num,timeout);
            switch (n)
            {
            case 0:
                logMessage(DEBUG,"time out...");
                break;
            case -1:
                logMessage(WARNING,"epoll wait error: %s",strerror(errno));
                break;
            default:
                //等待成功
                logMessage(DEBUG,"get a event");
                HandlerEvent(n);
                break;
            }
        }
        void start()
        {
            int timeout = -1;
            while (true)
            {
                loopOnce(timeout);
            }
            
        }
        ~EpollServer()
        {
            if(_listensock >=0) close(_listensock);
            if(_epfd>=0) close(_epfd);
            if(_revs) delete []_revs;
        }
    private:
        int _listensock;
        int _epfd;
        uint16_t _port;
        struct epoll_event *_revs;
        int _revs_num;
        func_t _HandlerRequest;
    };

}


#endif